<?php
class Vct_InController extends Apps_Controller_Action {
	public function indexAction() {
	    $this->disallowBacktrack();
		$layout = $this->_helper->layout();
		$layout->setLayout('layout-login');

		$storage = new Zend_Auth_Storage_Session();
		$data = $storage->read();
		if($data){
			$this->_redirect('/admin');
		}

		$users = new M_DbTable_User();
		$form = new F_Login();

		if($this->getRequest()->isPost()){
			if($form->isValid($_POST)){
				$data = $form->getValues();
				$data['password'] = md5($data['password']);

				$auth = Zend_Auth::getInstance();
				$authAdapter = new Zend_Auth_Adapter_DbTable($users->getAdapter(),'user');
				$authAdapter->setIdentityColumn('username')
							->setCredentialColumn('password');
				$authAdapter->setIdentity($data['username'])
							->setCredential($data['password']);
				$result = $auth->authenticate($authAdapter);
				if($result->isValid()){
					$storage = new Zend_Auth_Storage_Session();
					$storage->write($authAdapter->getResultRowObject());
					$n = new Zend_Session_Namespace($storage->getNamespace());
					$n->setExpirationSeconds('3600', null);
					
					$this->_helper->redirector(null, null, 'admin');
				} else {
					$form->getElement('username')->addError('Login failed.');
				}
			}
		}

		$this->view->form = $form;
	}
}